package com.shjn.squirrel.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.AccountReq;
import com.shjn.squirrel.bean.httpBean.ParamBean;
import com.shjn.squirrel.bean.httpBean.PayReq;
import com.shjn.squirrel.bean.httpBean.RespCommonResult;
import com.shjn.squirrel.bean.storageBean.BottleState;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.RecyclerInfoCache;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.shjn.squirrel.utils.SoundPlayUtils;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 回收员支付
 */
public class RecyclerPayFragment extends BaseFragment implements View.OnClickListener {

    private static RecyclerPayFragment instance;
    private TextView mCategory;
    private TextView mFullState;
    private TextView mQuantity;
    private TextView mPrice;
    private Button mConfirm;
    private TextView mBalance;


    public RecyclerPayFragment() {
    }

    public synchronized static RecyclerPayFragment getInstance() {
        if (instance == null) {
            instance = new RecyclerPayFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.recycler_payment, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        mActivity.mBackAndTimer.setOnBackListener(new BackAndTimerView.OnBackListener() {
            @Override
            public void onBack() {
                //返回回收员垃圾选择页面
                if (!RecyclerSelectFragment.getInstance().isAdded()) {
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, RecyclerSelectFragment.getInstance())
                            .commit();
                }
            }
        }).setBackVisibleState(true).setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
            @Override
            public void onTimerFinish() {
                //返回回收员垃圾选择页面
                if (!RecyclerSelectFragment.getInstance().isAdded()) {
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, RecyclerSelectFragment.getInstance())
                            .commit();
                }
            }
        }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mConfirm = (Button) mView.findViewById(R.id.btn_ok);
        mConfirm.setOnClickListener(this);
        mCategory = (TextView) mView.findViewById(R.id.tv_category);
        mFullState = (TextView) mView.findViewById(R.id.tv_full_value);
        mQuantity = (TextView) mView.findViewById(R.id.tv_garbage_value);
        mPrice = (TextView) mView.findViewById(R.id.tv_price_value);
        mBalance = (TextView) mView.findViewById(R.id.tv_balance);

        mCategory.setText(RecyclerInfoCache.garbageParam.getCategory() + "回收物");
        mFullState.setText(RecyclerInfoCache.garbageParam.getFullState());
        if (RecyclerInfoCache.garbageParam.getFullState().equals(Constant.full)) {
            mFullState.setTextColor(Color.parseColor("#f6546c"));
        } else {
            mFullState.setTextColor(Color.parseColor("#333333"));
        }
        if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
            mQuantity.setText(String.format("%.0f", RecyclerInfoCache.garbageParam.getQuantity()) + "个");
        } else {
            mQuantity.setText(String.format("%.2f", RecyclerInfoCache.garbageParam.getQuantity()) + "公斤");
        }
        mPrice.setText(String.format("%.2f", RecyclerInfoCache.garbageParam.getMoney()) + "元");

        //----------测试用-------------//
        //查询回收员当前余额
//        OkhttpHelper.postRequest(Constant.baseUrl + "machine/recycling/getRecyclingBalance",
//                new Gson().toJson(new AccountReq(RecyclerInfoCache.telNum)),
//                new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        Log.i("info", "getRecyclingBalance_onFailure: " + e.getMessage());
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
//                        if (result.getStateCode() == 1) {
//                            RecyclerInfoCache.balance = (double) result.getResult().get("balance");
//                            mActivity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (RecyclerPayFragment.getInstance().isAdded()) {
                                        mBalance.setText(String.format("%.2f", RecyclerInfoCache.balance) + "元");
//                                    }
//                                }
//                            });
//                        }
//                    }
//                });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                //禁用返回键，暂停倒计时器（上传支付订单可能有延时）
                mActivity.mBackAndTimer.setBackEnable(false).stop();

                //----------测试用-------------//
                //支付成功
                //通知主板开箱
//                                            mActivity.serialPortUtils.sendSerialPort("androidC54:" + Constant.numberMap.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3]) + ";");
                //添加到回收记录中
                RecyclerInfoCache.addRecord();
                //清除该垃圾桶状态
                if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
                    BottleState bottleState = LocalStorage.getBottleState(MyApplication.getInstance());
                    bottleState.setCount(0);
                    bottleState.setCanFullStatus(0);
                    LocalStorage.saveBottleState(MyApplication.getInstance(), bottleState);
                } else {
                    ArrayList<ParamBean> canState = RecyclerInfoCache.canState;
                    canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).setCanFullStatus(0);
                    canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).setQuantity(0);
                    canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).setWeight(0);
                    RecyclerInfoCache.canState = canState;
                }
                //跳转到开箱取货页面
                SoundPlayUtils.play(13);
                mActivity.getFragmentManager().beginTransaction()
                        .replace(R.id.mid, RecyclerOpenFragment.getInstance())
                        .commit();
                //启用返回键
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.mBackAndTimer.setBackEnable(true);
                    }
                });
                //----------测试用-------------//

                //上传支付订单
//                OkhttpHelper.postRequest(Constant.baseUrl + "machine/recycling/checkBalance",
//                        new Gson().toJson(new PayReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
//                                RecyclerInfoCache.telNum, Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3],
//                                RecyclerInfoCache.garbageParam.getQuantity())),
//                        new Callback() {
//                            @Override
//                            public void onFailure(Call call, IOException e) {
//                                Log.i("info", "checkBalance_onFailure: " + e.getMessage());
//                                //启用返回键，继续倒计时
//                                mActivity.runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
//                                    }
//                                });
//                            }
//
//                            @Override
//                            public void onResponse(Call call, Response response) {
//                                try {
//                                    RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
//                                    if (!RecyclerOpenFragment.getInstance().isAdded()) {
//                                        if (result.getStateCode() == 1) {
//                                            //支付成功
//                                            //通知主板开箱
////                                            mActivity.serialPortUtils.sendSerialPort("androidC54:" + Constant.numberMap.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3]) + ";");
//                                            //添加到回收记录中
//                                            RecyclerInfoCache.addRecord();
//                                            //清除该垃圾桶状态
//                                            if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
//                                                BottleState bottleState = LocalStorage.getBottleState(MyApplication.getInstance());
//                                                bottleState.setCount(0);
//                                                bottleState.setCanFullStatus(0);
//                                                LocalStorage.saveBottleState(MyApplication.getInstance(), bottleState);
//                                            } else {
//                                                ArrayList<ParamBean> canState = RecyclerInfoCache.canState;
//                                                canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).setCanFullStatus(0);
//                                                canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).setQuantity(0);
//                                                canState.get(Constant.categoryMap.get(RecyclerInfoCache.garbageParam.getCategory())[3] - 1).setWeight(0);
//                                                RecyclerInfoCache.canState = canState;
//                                            }
//                                            //跳转到开箱取货页面
//                                            SoundPlayUtils.play(13);
//                                            mActivity.getFragmentManager().beginTransaction()
//                                                    .replace(R.id.mid, RecyclerOpenFragment.getInstance())
//                                                    .commit();
//                                            //启用返回键
//                                            mActivity.runOnUiThread(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    mActivity.mBackAndTimer.setBackEnable(true);
//                                                }
//                                            });
//
//                                        } else {
//                                            //余额不足提示
//                                            WarningDialog.getInstance()
//                                                    .setMessage("您的余额不足")
//                                                    .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
//                                                        @Override
//                                                        public void onCloseDialog() {
//                                                            //启用返回键，继续倒计时
//                                                            mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
//                                                        }
//                                                    })
//                                                    .show(mActivity.getFragmentManager(), "recycler_pay_failed");
//
//                                        }
//                                    }
//                                } catch (IOException e) {
//                                    //启用返回键，继续倒计时
//                                    mActivity.runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
//                                        }
//                                    });
//                                }
//                            }
//                        });
                break;
            default:
                break;
        }
    }

}
